#include "SaveMenu.h"
#include "Utilities.h"
#include "PrintUtilities.h"
#include "ConfirmPanelMenu.h"
#include "MenuManager.h"
#include "GameControls.h"

#include <fstream>
#include <sstream>

#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>


SaveMenu::SaveMenu(MenuManager* const i_menuManager)
	: Menu(i_menuManager)
	, m_overwrite(false)
{
}

void SaveMenu::CalculateSlots() const
{
	for(size_t i = 0; i < Consts::NUM_SAVE_SLOT; ++i)
	{
		std::stringstream ss;
		ss << "./save/save_" << i << ".txt";

		std::fstream f(ss.str().c_str(), std::ios_base::in);

		m_slots[i] = f.is_open();


		if (m_slots[i])
		{
			struct _stat s;
			_stat(ss.str().c_str(), &s);
			
			char timebuf[26];
			ctime_s(timebuf, 26, &s.st_mtime);

			m_saveNames[i] = std::string(timebuf);
		}

		f.close();
	}
}

void SaveMenu::Draw() const
{
	CalculateSlots();

	std::cout	<< Print::Title(" SAVE MENU:") << std::endl << std::endl;

	std::stringstream ss;

	for(size_t i = 0; i < Consts::NUM_SAVE_SLOT; ++i)
	{
		ss << " " << i+1 << ") " << ((m_slots[i]) ? (m_saveNames[i]) : "empty slot.\n");
	}
	ss << "\n 0) Return to previous menu.";

	std::cout	<< Print::Options(ss.str()); 

	std::cout	<< " Selection: ";
}

bool SaveMenu::Input(const std::string& i_input)
{
	int res = Utilities::StringToInt(i_input);

	
	if(res == 0)
	{
		GetMM()->SetMenu(GetMM()->GetMainMenu());
		return true;
	}

	if(res < 0 || res > Consts::NUM_SAVE_SLOT)
		return false;

	--res;

	std::stringstream ss;
	ss << "./save/save_" << res << ".txt";
	m_fileName = ss.str();

	if(m_slots[res])
	{
		ConfirmPanelMenu* confirmPanel = static_cast<ConfirmPanelMenu*>(GetMM()->GetConfirmPanelMenu());
		confirmPanel->SetDelegate(this);
		GetMM()->PushMenu(confirmPanel);
	}
	else
	{
		GetMM()->GetGameControls()->Save(ss.str().c_str());
		GetMM()->SetMenu(GetMM()->GetMainMenu());
	}
	return true;

}

void SaveMenu::PanelWillClose(bool i_yesOrNo)
{
	if (i_yesOrNo)
	{
		GetMM()->GetGameControls()->Save(m_fileName.c_str());
	}
}